﻿function loadRecipes(paging, pageno, userid, recipeid, user, isSearch) {
    var url = "";
    var data = "";
    if (userid == '') {
        userid = '0';
        url = "PIMService.asmx/GetRecipeUserByNamePaging";
        data = "{'RecipeName':'" + $('.suggest').val() + "','UserId':'" + userid + "','page_no':'" + pageno + "','page_lenght':'" + paging + "'}";
    }
    else if (recipeid == '') {
        url = "PIMService.asmx/GetRecipeUserByNamePaging";
        data = "{'RecipeName':'" + $('.suggest').val() + "','UserId':'" + userid + "','page_no':'" + pageno + "','page_lenght':'" + paging + "'}";
    }
    else {
        url = "PIMService.asmx/GetRecipeUserByNamePagingWithoutRecipe";
        data = "{'RecipeName':'" + $('.suggest').val() + "','UserId':'" + userid + "','page_no':'" + pageno + "','page_lenght':'" + paging + "','recipeid':'" + recipeid + "'}";
    }

    $('#p' + pageno).addClass('active');
    for (var i = 0; i < paging; i++) {
        if(i!=pageno)
            $('#p' + i).removeClass('active');
    }

    $.ajax({
        type: "POST",
        url: url,
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            if (response.d.length > 0) {
                BindRecipe(response, userid, user);
            }
            else {
                $('#loading').hide();
                var divbg = document.getElementById('bg');
                divbg.style.visibility = "hidden";
                if (isSearch == 1) {
                    $("#dialog-message").dialog({
                        resizable: false,
                        height: 250,
                        width: 500,
                        modal: true,
                        buttons: {
                            Ok: function () {
                                $('.suggest').val('');
                                $('#btnDelete').css('display', 'none');
                                $(this).dialog("close");
                            }
                        }
                    });
                }
            }
        },
        error: function (msg) { alert('Connect to database is break. Please check connection info!'); }
    });

}

function BindRecipe(response, userid, user) {
    var recipe = response.d;
    var html = "";
    $('#leftpanel').html(html);
    html = "<ul class='ul02'>";
    
    for (var i = 0; i < recipe.length; i++) {
        var varObjectID = recipe[i].RecipeID;
        var OldUser = recipe[i].UserID;
        var varObjectName;
        var varObjectNameFull;
        if (recipe[i].RecipeName != null) {
            varObjectName = recipe[i].RecipeName.substring(0, 10);

            varObjectNameFull = recipe[i].RecipeName;
            if (varObjectNameFull.length > 10) varObjectName = varObjectName + ' ..';
        }
        else {
            varObjectName = 'No Name..';
            varObjectNameFull = 'No Name';
        }
        var varUserName = recipe[i].UserName;
        var rating = recipe[i].RecipeRating;
        var serving = recipe[i].Serving;
        var image = recipe[i].RecipeImage;
        var description = recipe[i].Description;
        var RecipeIngredientList = recipe[i].IngredientNameString;
        var DepartmentList = recipe[i].DepartNameString;
        var imageLink = recipe[i].LinkImage;
        if (imageLink == '') imageLink = 'images/PlanItMeal_NoImage.png';
        if (image == '') image = 'images/PlanItMeal_NoImage.png';
        
        rating = "'" + rating + "'";
        description = description.replace('"', '').replace('"', '').replace('"', '').replace('"', '');
        varObjectName = varObjectName.replace('"', '').replace('"', '').replace('"', '').replace('"', '');
        varObjectNameFull = varObjectNameFull.replace('"', '').replace('"', '').replace('"', '').replace('"', '');

        if (image != null) {

            html += '<li id="' + varObjectID + '">';
            html += '<p title="' + varObjectNameFull + '" onclick="javascript:CallRecipeDetail(' + varObjectID + ')" class="text">' + varObjectNameFull + '</p>';
            html += '<p class="mar_b04"><a href="#"><img class="tooltip" ondblclick="javascript:CallRecipeDetail(' + varObjectID + ')" src="' + image + '" OnError="this.src=\'images/PlanItMeal_NoImage.png\';" alt="" width="220" height="220" title="<b>Name: </b>' + varObjectNameFull + '</br><b>Description: </b>' + description + '</br><b>Author: </b>' + varUserName + '</br><div class=basic data-average=' + rating + ' data-id=1></div>"/></a></p>';
            html += '<div class="clearfix">';
            if (userid == '0') {
                if (user!='')
                    html += '<p class="img_l"><img title="Add to my recipe" onclick="javascript:AddToMyRecipe(' + varObjectID + ',' + user + ',' + OldUser + ');" id="staricon" src="images/icon1.jpg" alt="" width="13" height="12" /></p>';
            }
            html += '<p class="img_r"><img title="Add to grocery list" id="plusicon" src="images/icon2.jpg" alt="" width="13" height="13" /></p>';
            html += '</div>';
            html += '</li>';
            html += '<div id="ingredientList' + varObjectID + '" style="display:none">' + RecipeIngredientList + '</div>';
            html += '<div id="departmentList' + varObjectID + '" style="display:none">' + DepartmentList + '</div>';
            html += '<div id="Serving' + varObjectID + '" style="display:none">' + serving + '</div>';   
        }
    }
    html += '</ul>';
    $('#leftpanel').append(html);
    $('#loading').hide();
    var divbg = document.getElementById('bg');
    divbg.style.visibility = "hidden";
    init_tooltip();
    dropdrag();
}

function ImageExist(url) {
    var img = new Image();
    img.src = url;
    return img.height;
}

function LoadRecipesPaging(paging, iduser, pageno, AllRecipe, user) {
//    alert(iduser);
    var url = "";
    var data = "";
    url = "PIMService.asmx/GetRecipeUserByName";
    data = "{'RecipeName':'" + $('.suggest').val() + "','UserId':'" + iduser + "'}";
    
    $.ajax({
        type: "POST",
        url: url,
        data: data,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            
            BindRecipesPaging(response, paging, pageno, AllRecipe, iduser, user);
        },
        error: function (msg) { alert('Connect to database is break. Please check connection info!'); }
    });
}

function BindRecipesPaging(response, paging, pageno, AllRecipe, userid,user) {
    var recipeid = "0";
//    alert(userid);
    if (userid == undefined) userid = "0";
    if (user == undefined || user=='') user = "0";
    var recipepagin = response.d;
    var rownumber = 0;
    var last = 0;
    if (paging == '') paging = 10;
    var count = recipepagin.length;
    rownumber = parseInt(count) / parseInt(paging);
    rownumber = Math.round(parseInt(rownumber));
    last = count % paging;
    if (last > 0) rownumber = rownumber + 1;
    var html = "";
    html += '<div class="pagination">';
    for (var i = 1; i <= rownumber; i++) {
//        if (parseInt(pageno) == i)
//            html += '<a id="p' + i.toString() + '" href="' + AllRecipe + '.aspx?page=' + i.toString() + '&value=' + $('.suggest').val() + '" class="page active">' + i.toString() + '</a>';
//        else
//                    html += '<a id="p' + i.toString() + '" href="' + AllRecipe + '.aspx?page=' + i.toString() + '&value=' + $('.suggest').val() + '" class="page">' + i.toString() + '</a>';
        if (parseInt(pageno) == i)
            html += '<a id="p' + i.toString() + '" onclick="javascript:loadRecipes(' + paging + ',' + i.toString() + ',' + userid + ',' + recipeid + ',' + user + ')" class="page active">' + i.toString() + '</a>';
        else
            html += '<a id="p' + i.toString() + '" onclick="javascript:loadRecipes(' + paging + ',' + i.toString() + ',' + userid + ',' + recipeid + ',' + user + ')" class="page">' + i.toString() + '</a>';
    }
    html += '</div>';
    $('#divpaging').html(html);
}

function AddToMyRecipe(RecipeId, UserId, OldUser) {
    $("#" + RecipeId).remove();
    $.ajax({
        type: "POST",
        url: "PIMService.asmx/InsertMyRecipe",
        data: "{'_recipeId':'" + RecipeId + "','_userId':'" + UserId + "','_oldUser':'" + OldUser + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            result = response.d;
            CreateNutrition(UserId, RecipeId);
        },
        error: function (msg) {
        }
    });


}

function CallRecipeDetail(varObjectID) {
    self.location = "NewRecipe.aspx?RecipeId=" + varObjectID;
}

function BindSuggestion() {
    $.ajax({
        type: "POST",
        url: "PIMService.asmx/GetRecipeUser",
        data: "{'UserId':'0'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var availableTags = '';
            var object = response.d;
            for (var i = 0; i < object.length; i++) {
                var varObjectNameFull;
                varObjectNameFull = object[i].RecipeName;

                var Sugges = varObjectNameFull;
                availableTags += Sugges + ",";
            }
            availableTags = availableTags.substring(0, availableTags.length - 1);
           
            var suggestion = availableTags.split(',');

            $(".suggest").autocomplete({
                source: suggestion
            });
        }
    });
}

function BindGrahpSuggestion(userid) {
    $.ajax({
        type: "POST",
        url: "PIMService.asmx/GetSearchRecipeName",
        data: "{'UserId':'" + userid + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
         
            var availableTags = '';
            var object = response.d;
            for (var i = 0; i < object.length; i++) {
                var varObjectNameFull;
                varObjectNameFull = object[i].RecipeName;

                var Sugges = varObjectNameFull;
                availableTags += Sugges + ";";
            }
            availableTags = availableTags.substring(0, availableTags.length - 1);

            var suggestion = availableTags.split(';');
            
            $(".suggestReport").autocomplete({
                source: suggestion
              
            });
        }
    });
}
function CreateMealPlan(userid, recipelist, MealPlanName) {
    if (userid == '') {
        alert('Please login for create meal plan!');
    }
    else if (MealPlanName == '') {
        alert('Please input name of Meal Plan!');
    }
    else if ($('#inputMealPlanId').val() == '') {
        alert('Recipe is not avalable!');
    }
    else {
        var RecipeIDList = recipelist.split(',');
        $.ajax({
            type: "POST",
            url: "PIMService.asmx/CreateMealPlan",
            data: "{'UserID':'" + userid + "','MealPlanName':'" + MealPlanName + "','recipeidlist':'" + RecipeIDList + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (response) {
                alert('Create meal plan is success!');
                $('#mealplanName').val('');
                $('#hdMealPlanId').val('');
                var str = response.d;
            },
            error: function (response) {
            }
        });
    }
}

function CreateNutrition(userid, recipelist) {
    var RecipeIDList = recipelist.split(',');
    $.ajax({
        type: "POST",
        url: "PIMService.asmx/CreateNutrition",
        data: "{'UserID':'" + userid + "','recipeidlist':'" + RecipeIDList + "'}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var str = response.d;
        },
        error: function (response) {
        }
    });
}

//function LoadRecipesPaging(paging, userid, pageno, AllRecipe) {
//    var url = "";
//    var data = "";

//    url = "PIMService.asmx/GetRecipeUserByName";
//    data = "{'RecipeName':'" + $('.suggest').val() + "','UserId':'" + userid + "'}";

//    $.ajax({
//        type: "POST",
//        url: url,
//        data: data,
//        contentType: "application/json; charset=utf-8",
//        dataType: "json",
//        success: function (response) {
//            BindRecipesPaging(response, paging, pageno, AllRecipe);
//        },
//        error: function (msg) { alert('Connect to database is break. Please check connection info!'); }
//    });
//}

//function BindRecipesPaging(response, paging, pageno, AllRecipe) {
//    var recipepagin = response.d;
//    var rownumber = 0;
//    var last = 0;
//    if (paging == '') paging = 10;
//    var count = recipepagin.length;
//    rownumber = parseInt(count) / parseInt(paging);
//    rownumber = Math.round(parseInt(rownumber));
//    last = count % paging;
//    if (last > 0) rownumber = rownumber + 1;
//    var html = "";
//    html += '<div class="pagination">';
//    for (var i = 1; i <= rownumber; i++) {
//        if (parseInt(pageno) == i)
//            html += '<a id="p' + i.toString() + '" href="' + AllRecipe + '.aspx?page=' + i.toString() + '&value=' + $('.suggest').val() + '" class="page active">' + i.toString() + '</a>';
//        else
//            html += '<a id="p' + i.toString() + '" href="' + AllRecipe + '.aspx?page=' + i.toString() + '&value=' + $('.suggest').val() + '" class="page">' + i.toString() + '</a>';
//    }
//    html += '</div>';
//    $('#divpaging').html(html);
//}